import os
import sys
import re
import codecs
import shutil


def write_dummy_file(src_file, dst_filename, if_only_id = False):
    if not os.path.exists(src_file):
        raise FileNotFoundError

    fp = codecs.open(filename=dst_filename, mode='w', encoding='utf8')
    for line in codecs.open(filename=src_file, mode='r'):
        id, context = re.split("\s+", line)[0], re.split("\s+", line)[1]
        content = re.split("\s+", line)[1]
        if if_only_id:
            fp.write('{} {}\n'.format(id, id))
        else:
            fp.write('{} {}\n'.format(id, content))

    fp.close()


def make_fixed_folder(data_dir, ali_scp, dst_dir):
    feats = data_dir + "//" + "feats.scp"
    if not os.path.exists(feats) or not os.path.exists(ali_scp):
        raise FileNotFoundError

    temp_dir = dst_dir
    if not os.path.exists(temp_dir):
        os.mkdir(temp_dir)

    shutil.copy(feats, temp_dir)
    dst_utt2spk = temp_dir + "//" + "utt2spk"
    dst_spk2utt = temp_dir + "//" + "spk2utt"
    dst_wavscp = temp_dir + "//" + "wav.scp"
    dst_text = temp_dir + "//" + "text"
    write_dummy_file(ali_scp, dst_spk2utt, True)
    write_dummy_file(ali_scp, dst_utt2spk, True)
    write_dummy_file(ali_scp, dst_wavscp, False)
    write_dummy_file(ali_scp, dst_text, False)


if __name__ == '__main__':
    if len(sys.argv) < 3:
        print('{} {}\n'.format("<dir_dir>", "<ali.scp> <dst_dir>"))
        sys.exit(-1)
    data_dir, ali_scp, merged_dir = sys.argv[1], sys.argv[2], sys.argv[3]
    print('Command line : {}\n'.format(sys.argv[1:]))
    make_fixed_folder(data_dir=data_dir, ali_scp=ali_scp, dst_dir=merged_dir)
    print("Everything is OK\n")

